
# install and load packages

if(!require(devtools)){
  install.packages("devtools")
  library(devtools)
}

if(!require(tidyverse)){
  install.packages("tidyverse")
  library(tidyverse)
}

if(!require(countrycode)){
  install.packages("countrycode")
  library(countrycode)
}

if(!require(democracyData)){
  devtools::install_github("xmarquez/democracyData")
  library(democracyData)
}


# load vdem and eiu datasets 

# load vdem

# 1. Get access to the vdem-extended 8 .csv file: https://www.v-dem.net/en/data/data-version-8/#
# 2. Unzip the file to the current working directory
# 3. Load the vdem .csv file
vdem <- read_csv("V-Dem-CY+Others-v8.csv")

# load eiu 

# The eiu file is available from the democracy data package 
eiu <- data.frame(eiu)

# prepare vdem dataset 
vdem_soc <- vdem %>% select(
                 country_name,
                 year,
                 COWcode,
                 v2cseeorgs, # CSOentryandexit
                 v2csreprss, # CSOrepression
                 v2cscnsult, # CSOconsultation
                 v2csstruc_2,# CSOstructure
                 v2csprtcpt, # CSO participatory environment
                 v2csgender, # CSO women’s participation 
                 v2csantimv, # CSO anti-system movements
                 v2csanmvch_0, # CSO anti-system movement character
                 v2xcs_ccsi, # Core Civil Society Index (CCSI
                 v2x_cspart, # Civil Society Participation Index
                 e_migdppc,  # GDP Per Capita
                 v2xel_frefair # Clean Election Index
                 )

vdem_soc <- vdem_soc %>% mutate(
                         iso3c = countrycode(country_name,"country.name","iso3c")) %>% 
                         select(-COWcode) %>% 
                         mutate(year = as.numeric(year)) 

# prepare eiu dataset 
eiu_soc <- eiu %>% 
       mutate(iso3c = countrycode(cown,"cown","iso3c")) %>%
       select(iso3c,year,eiu) %>%
       mutate(year = as.numeric(year))

# merge vdem and eiu 
civilsociety <- left_join(vdem_soc, eiu_soc, by=c("iso3c","year")) 
                 
# prepare authoritarian regime 
authoritarian_regime <- civilsociety %>% filter(eiu < 3.99)

# prepare hybrid regime 
hybrid_regime <- civilsociety %>% filter(eiu > 3.99 & eiu < 6.00) 

# prepare flawed democracy 
flawed_democracy  <- civilsociety %>% filter(eiu > 5.99 & eiu < 8.00) 

# prepare full democracy
full_democracy  <- civilsociety %>% filter(eiu > 7.99) 

# export datasets 
save(authoritarian_regime, hybrid_regime, flawed_democracy, full_democracy,
     file = "data/civilsociety.RData")


     
